import java.util.ArrayList;

/**
 * @description:
 * @Author: wuzhenbin
 * @CreateTime: 2025-02-15
 */
public class leetcode_142 {
    public static void main(String[] args) {

    }

    public ListNode detectCycle(ListNode head) {
        if(hasCycle(head)){
            ArrayList<ListNode> list = new ArrayList<>();
            ListNode cur = head;
            while(!list.contains(cur)){
                list.add(cur);
                cur = cur.next;
            }
            return cur;
        }
        return null;
    }

    public boolean hasCycle(ListNode head) {
        ListNode headNode = new ListNode(0);
        headNode.next = head;
        ListNode slow = headNode;
        ListNode fast = head;
        while(fast!=slow&&fast!=null&&slow!=null&&fast.next!=null){
            fast = fast.next;
            slow = slow.next;
            fast = fast.next;
        }
        if(fast == slow || (fast!=null&&fast.next!=null&&fast.next==slow))return true;
        return false;
    }
    public ListNode detectCycle1(ListNode head) {
        ListNode headNode = new ListNode(0);
        headNode.next = head;
        ListNode slow = headNode;
        ListNode fast = head;
        while(fast!=slow&&fast!=null&&slow!=null&&fast.next!=null){
            fast = fast.next;
            slow = slow.next;
            fast = fast.next;
        }
        if(fast == slow || (fast!=null&&fast.next!=null&&fast.next==slow)){
        // 步骤 2: 找到相遇点后，寻找入环的起点
            ListNode entry = head;
            while (entry != slow) {
                entry = entry.next;
                slow = slow.next;
            }
            return entry;  // 返回入环的第一个节点
        }
        return null;
    }


    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
